package com.york.subject.domain.handler.subject;

import com.alibaba.fastjson.JSON;
import com.google.common.base.Preconditions;
import com.york.subject.common.enums.IsDeletedFlagEnum;
import com.york.subject.common.enums.SubjectInfoTypeEnum;
import com.york.subject.domain.convert.JudgeSubjectConverter;
import com.york.subject.domain.convert.RadioSubjectConverter;
import com.york.subject.domain.entity.SubjectAnswerBO;
import com.york.subject.domain.entity.SubjectInfoBO;
import com.york.subject.domain.entity.SubjectOptionBO;
import com.york.subject.infra.basic.entity.SubjectJudge;
import com.york.subject.infra.basic.entity.SubjectRadio;
import com.york.subject.infra.basic.service.SubjectRadioService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.LinkedList;
import java.util.List;

/**
 * 单选题题目的策略类
 */
@Slf4j
@Component
public class RadioTypeHandler implements SubjectTypeHandler {

    @Resource
    private SubjectRadioService subjectRadioService;

    @Override
    public SubjectInfoTypeEnum getHandlerType() {
        return SubjectInfoTypeEnum.RADIO;
    }

    /**
     * 插入单选题
     */
    @Override
    public void add(SubjectInfoBO subjectInfoBO) {
        List<SubjectRadio> subjectRadioList = new LinkedList<>();
        if (log.isInfoEnabled()) {
            log.info("RadioTypeHandler.add.bo:{}", JSON.toJSONString(subjectInfoBO));
        }
        Preconditions.checkNotNull(subjectInfoBO.getOptionList(), "单选题选项不能为空");

        // 依据 private List<SubjectAnswerBO> optionList，所以option就是SubjectAnswerBO对象
        // 每一个SubjectAnswerBo对象属性：optionType optionContent isCorrect
        // 处于Domain这一层，就是将BO转成实体，所以需要组装最后的subjectRadio，即用传来的BO给它添加属性
        subjectInfoBO.getOptionList().forEach(option -> {
            SubjectRadio subjectRadio = RadioSubjectConverter.INSTANCE.convertBoToEntity(option);
            subjectRadio.setSubjectId(subjectInfoBO.getId());
            subjectRadio.setIsDeleted(IsDeletedFlagEnum.UN_DELETED.getCode());
            subjectRadioList.add(subjectRadio);
        });
        subjectRadioService.batchInsert(subjectRadioList);
    }

    /**
     * 返回题目信息
     */
    @Override
    public SubjectOptionBO query(Long subjectId) {
        SubjectRadio subjectRadio = new SubjectRadio();
        subjectRadio.setSubjectId(subjectId);
        // 先查到题目
        List<SubjectRadio> resultList = subjectRadioService.queryByCondition(subjectRadio);
        // 对题目的答案赋值，用转换器转换格式即可
        List<SubjectAnswerBO> subjectAnswerBOList = RadioSubjectConverter.INSTANCE.convertEntityListToBOList(resultList);
        SubjectOptionBO subjectOptionBO = new SubjectOptionBO();
        subjectOptionBO.setOptionList(subjectAnswerBOList);
        return subjectOptionBO;
    }
}
